package Server;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;

import javax.net.*;

import Journal.*;

/*
 * ClassServer.java -- a simple file server that can serve
 * Http get request in both clear and secure channel
 */

/**
 * Based on ClassServer.java in tutorial/rmi
 */
public abstract class ClassServer implements Runnable {
	private JournalHandler jh = new JournalHandler();
	private ServerSocket server = null;
	private Log log;

	/**
	 * Constructs a ClassServer based on <b>ss</b> and obtains a file's
	 * bytecodes using the method <b>getBytes</b>.
	 * 
	 */
	protected ClassServer(ServerSocket ss) {
		server = ss;
		newListener();
		log = new Log();

	}

	/**
	 * The "listen" thread that accepts a connection to the server, parses the
	 * header to obtain the file name and sends back the bytes for the file (or
	 * error if the file is not found or the response was malformed).
	 */
	public void run() {

		Socket socket;

		// accept a connection
		try {
			socket = server.accept();
			System.out.println("Client connected");
		} catch (IOException e) {
			System.out.println("Class Server died: " + e.getMessage());
			e.printStackTrace();
			return;
		}

		// create a new thread to accept the next connection
		newListener();

		try {
			OutputStream rawOut = socket.getOutputStream();

			PrintWriter out = new PrintWriter(new BufferedWriter(
					new OutputStreamWriter(rawOut)));
			try {

				BufferedReader in = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));
				String command = in.readLine();

				InputStream inputstream = socket.getInputStream();
				InputStreamReader inputstreamreader = new InputStreamReader(
						inputstream);
				BufferedReader bufferedreader = new BufferedReader(
						inputstreamreader);



				/*
				 *  Skickar kommandot till stringIdentifier som utför kommandot och returnerar
				 *  vilket kommando det var samt eventuell extra information. Svaret baseras på 
				 *  svaret från stringIdentifier
				 */
				
				String commandString = null;
				String identifiedString;
				Scanner scan;
				while ((commandString = bufferedreader.readLine()) != null) {
					
					log.log("doc1", commandString);
					
					identifiedString = stringIdentifier(commandString);
					scan = new Scanner(identifiedString);
					String first = scan.next();
					
					if (first.equals("edit_j")){
						out.println(scan.next());
					}else if (first.equals( "get_j")){
						out.println(scan.next());
					}else if (first.equals("del_j")){
						out.println(scan.next());
					}

					
					
					
					
					
//					log.log("doc1", string);
//					out.println("doc1#nurse1#comment1#patient1#12345");
//					out.flush();
				}
				

			} catch (Exception e) {
				out.println("error: " + e.getMessage());
				out.flush();
			}

		} catch (IOException ex) {
			System.out.println("error writing response: " + ex.getMessage());
			ex.printStackTrace();

		} finally {
			try {
				socket.close();
			} catch (IOException e) {
			}
		}

	}

	private String stringIdentifier(String str) {
		String[] temp;
		String delimiter = "#";
		temp = str.split(delimiter);
		int patientID = Integer.parseInt(temp[4]);

		if (temp[0].equals("new_pat")) {
			jh.createJournal(temp[1], temp[2], temp[3], patientID);
		}else if(temp[0].equals("edit_j")){
			if(jh.editJournal(temp[1], temp[2], temp[3], patientID)){
				return "edit_j ok";
			}else{
				return "edit_j fail";
			}
		} else if (temp[0].equals("get_j")) {
			patientID = Integer.parseInt(temp[1]);
			return "get_j " + jh.getJournal(patientID);
			
			
		} else if (temp[0].equals("del_j")) {
			if (jh.removeJournal(patientID)) {
				return "del_j ok";
			} else {
				return "del_j fail";
			}

		} else {
			System.out.println("failure to parse input string");
		}
		return temp[0];

	}

	/**
	 * Create a new thread to listen.
	 */
	private void newListener() {
		(new Thread(this)).start();
	}

}